#!/bin/bash

# EMS-CPP-V1 一键启动脚本
# Quick Start Script for EMS-CPP-V1
# 功能: 检查环境、构建Web前端、编译C++程序并启动系统

set -e

# 获取脚本目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 项目信息
PROJECT_NAME="EMS 能源管理系统"
VERSION="v1.0.0"
FORCE_SKIP_WEB=false # 由 --skip-web 或环境变量 SKIP_WEB=1/true 触发
APP_PID=""          # 主程序PID，便于退出时清理

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_header() {
    echo -e "${PURPLE}=== $1 ===${NC}"
}

log_step() {
    echo -e "${CYAN}[STEP $1]${NC} $2"
}

# 显示欢迎信息
show_welcome() {
    clear
    echo -e "${PURPLE}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                   EMS 能源管理系统                          ║"
    echo "║               Energy Management System                       ║"
    echo "║                     $VERSION                                 ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    echo -e "${CYAN}🏭 轻量级工业级能源管理解决方案${NC}"
    echo -e "${CYAN}⚡ 支持 Modbus TCP/RTU、MQTT 等多种协议${NC}"
    echo -e "${CYAN}🌐 内置 Web 管理界面，支持实时监控和配置${NC}"
    echo ""
}

# 检查系统兼容性
check_system() {
    log_header "系统兼容性检查"
    
    # 检查操作系统
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="Linux"
        DISTRO=$(lsb_release -si 2>/dev/null || echo "Unknown")
        log_info "操作系统: $OS ($DISTRO)"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macOS"
        VERSION=$(sw_vers -productVersion 2>/dev/null || echo "Unknown")
        log_info "操作系统: $OS ($VERSION)"
    else
        log_error "不支持的操作系统: $OSTYPE"
        echo "支持的系统: Linux, macOS"
        exit 1
    fi
    
    # 检查CPU架构
    ARCH=$(uname -m)
    log_info "CPU架构: $ARCH"
    
    # 检查内存
    if command -v free &> /dev/null; then
        MEMORY=$(free -h | awk '/^Mem:/ { print $2 }')
        log_info "系统内存: $MEMORY"
    elif [[ "$OS" == "macOS" ]]; then
        MEMORY=$(sysctl -n hw.memsize | awk '{print int($1/1024/1024/1024)"GB"}')
        log_info "系统内存: $MEMORY"
    fi
    
    log_success "系统兼容性检查通过"
}

install_system_dependencies() {
    log_header "安装系统依赖"

    if command -v apt-get >/dev/null 2>&1; then
        local packages=(build-essential cmake ninja-build pkg-config libssl-dev libmosquitto-dev)
        local missing=()

        for pkg in "${packages[@]}"; do
            if ! dpkg -s "$pkg" >/dev/null 2>&1; then
                missing+=("$pkg")
            fi
        done

        if [ ${#missing[@]} -gt 0 ]; then
            log_info "准备安装缺失的软件包: ${missing[*]}"
            sudo apt-get update
            sudo apt-get install -y "${missing[@]}"
            log_success "系统依赖安装完成"
        else
            log_info "所有必需软件包已安装"
        fi
    else
        log_warning "未检测到 apt-get，跳过自动安装，请手动确保构建依赖已安装"
    fi
}

# 快速依赖检查
quick_dependency_check() {
    log_header "快速依赖检查"
    
    local missing_deps=()
    
    # 检查基础工具
    local basic_tools=("cmake" "make" "git" "curl")
    for tool in "${basic_tools[@]}"; do
        if ! command -v "$tool" &> /dev/null; then
            missing_deps+=("$tool")
        else
            log_info "✓ $tool"
        fi
    done
    
    # 检查编译器
    if command -v g++ &> /dev/null; then
        log_info "✓ g++ ($(g++ --version | head -n1 | grep -oE '[0-9]+\.[0-9]+' | head -1))"
    elif command -v clang++ &> /dev/null; then
        log_info "✓ clang++ ($(clang++ --version | head -n1 | grep -oE '[0-9]+\.[0-9]+' | head -1))"
    else
        missing_deps+=("g++/clang++")
    fi
    
    # 检查Node.js
    if command -v node &> /dev/null; then
        NODE_VERSION=$(node --version)
        NODE_MAJOR=$(echo $NODE_VERSION | cut -d'.' -f1 | cut -d'v' -f2)
        if [ "$NODE_MAJOR" -ge 16 ]; then
            log_info "✓ Node.js $NODE_VERSION"
        else
            log_warning "Node.js版本过低: $NODE_VERSION (需要 >= 16.0)"
            missing_deps+=("node>=16")
        fi
    else
        missing_deps+=("node")
    fi
    
    # 检查Python3
    if command -v python3 &> /dev/null; then
        PYTHON_VERSION=$(python3 --version)
        log_info "✓ $PYTHON_VERSION"
    else
        missing_deps+=("python3")
    fi
    
    # 如果有缺失的依赖
    if [ ${#missing_deps[@]} -gt 0 ]; then
        log_error "缺少以下依赖:"
        for dep in "${missing_deps[@]}"; do
            echo "  - $dep"
        done
        echo
        log_info "建议运行完整的环境检查和安装:"
        echo "  $PROJECT_ROOT/scripts/deploy-dev.sh"
        echo
        read -p "是否继续尝试构建? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log_info "已取消启动"
            exit 1
        fi
    else
        log_success "所有依赖检查通过"
    fi
}

# 确保嵌入资源与构建产物一致（避免前端chunk不匹配导致404）
ensure_web_embedding_consistent() {
    # 仅当存在嵌入头文件与构建产物时才检查
    local EMBED_HEADER="$PROJECT_ROOT/src/web/EmbeddedWebResources.h"
    local BUILD_INDEX_HTML="$PROJECT_ROOT/build/web/index.html"
    if [ ! -f "$EMBED_HEADER" ] || [ ! -f "$BUILD_INDEX_HTML" ]; then
        return 0
    fi

    # 从头文件与构建index.html中提取 index-*.js 的路径
    local HDR_INDEX
    local BUILD_INDEX
    HDR_INDEX=$(grep -Eo '/assets/index-[A-Za-z0-9_-]+\.js' "$EMBED_HEADER" | head -n 1 || true)
    BUILD_INDEX=$(grep -Eo '/assets/index-[A-Za-z0-9_-]+\.js' "$BUILD_INDEX_HTML" | head -n 1 || true)

    if [ -n "$HDR_INDEX" ] && [ -n "$BUILD_INDEX" ] && [ "$HDR_INDEX" != "$BUILD_INDEX" ]; then
        log_warning "检测到嵌入资源与前端构建不一致: header=$HDR_INDEX, build=$BUILD_INDEX"
        log_step "X" "重新生成嵌入资源并编译后端（修复chunk不匹配）"
        if $WEB_AVAILABLE && [ -f "$PROJECT_ROOT/scripts/build-web.sh" ]; then
            (cd "$PROJECT_ROOT" && ./scripts/build-web.sh --skip-lint)
        fi
        (cd "$PROJECT_ROOT" && ./scripts/build.sh build --skip-web)
    fi
}

# 检查项目结构
check_project_structure() {
    log_header "检查项目结构"
    
    local required_dirs=("src" "include" "config" "scripts")
    local required_files=("CMakeLists.txt" "scripts/build.sh")
    
    # 检查目录
    for dir in "${required_dirs[@]}"; do
        if [ -d "$PROJECT_ROOT/$dir" ]; then
            log_info "✓ $dir/"
        else
            log_error "缺少目录: $dir/"
            exit 1
        fi
    done
    
    # 检查文件
    for file in "${required_files[@]}"; do
        if [ -f "$PROJECT_ROOT/$file" ]; then
            log_info "✓ $file"
        else
            log_error "缺少文件: $file"
            exit 1
        fi
    done
    
    # 检查Web项目
    if [ -d "$PROJECT_ROOT/web/frontend" ] && [ -f "$PROJECT_ROOT/web/frontend/package.json" ]; then
        log_info "✓ web/frontend/"
        WEB_AVAILABLE=true
    else
        log_warning "Web前端项目不存在，将跳过Web构建"
        WEB_AVAILABLE=false
    fi
    # 若显式要求跳过 Web，则覆盖自动检测
    if [ "$FORCE_SKIP_WEB" = true ] || [ "${SKIP_WEB}" = "1" ] || [ "${SKIP_WEB}" = "true" ]; then
        log_warning "已启用 SKIP_WEB，跳过Web构建"
        WEB_AVAILABLE=false
    fi
    
    log_success "项目结构检查完成"
}

# 智能构建策略选择
choose_build_strategy() {
    log_header "选择构建策略"

    # 检查是否存在构建产物
    local cpp_built=false
    local web_built=false
    local web_required=true

    if [ -f "$PROJECT_ROOT/build/bin/ems-cpp-v1" ]; then
        cpp_built=true
        log_info "发现已构建的C++可执行文件"
    fi

    if [ -d "$PROJECT_ROOT/build/web" ] && [ "$(ls -A "$PROJECT_ROOT/build/web" 2>/dev/null)" ]; then
        web_built=true
        log_info "发现已构建的Web文件"
    fi

    if [ "$WEB_AVAILABLE" != true ] || [ "$FORCE_SKIP_WEB" = true ]; then
        web_required=false
    fi

    # 根据情况选择策略
    # 检查前端是否需要重建：若前端源码较新，或嵌入头文件缺失，则默认重建Web
    local EMBED_HEADER="$PROJECT_ROOT/src/web/EmbeddedWebResources.h"
    local NEED_WEB_REBUILD=false
    if [ "$web_required" = true ] && [ -d "$PROJECT_ROOT/web/frontend" ]; then
        if [ ! -f "$EMBED_HEADER" ]; then
            NEED_WEB_REBUILD=true
        else
            # 任意前端源码较嵌入头文件更新，则需要重建
            if find "$PROJECT_ROOT/web/frontend" -type f \( -name "*.vue" -o -name "*.js" -o -name "*.ts" -o -name "*.css" -o -name "*.scss" -o -name "*.html" -o -name "*.json" \) -newer "$EMBED_HEADER" | grep -q .; then
                NEED_WEB_REBUILD=true
            fi
        fi
    fi

    local direct_allowed=false
    if $cpp_built; then
        if $web_built; then
            direct_allowed=true
        elif [ "$web_required" = false ]; then
            direct_allowed=true
        fi
    fi

    while true; do
        echo
        log_info "构建选项:"
        if $direct_allowed; then
            local direct_label="  1) 直接启动 (跳过构建)"
            if [ "$web_required" = true ] && $NEED_WEB_REBUILD; then
                direct_label+=" [建议重新构建Web]"
            elif [ "$web_required" = false ] && ! $web_built; then
                direct_label+=" [已跳过Web构建]"
            fi
            echo "$direct_label"
        else
            if [ "$web_required" = true ]; then
                echo "  1) 直接启动 (不可用: 未发现完整构建产物)"
            else
                echo "  1) 直接启动 (不可用: 后端未构建)"
            fi
        fi
        echo "  2) 重新构建并启动 (完整构建)"
        echo "  3) 仅重新构建Web前端并启动"
        echo "  4) 仅重新构建后端并启动"
        echo "  5) 退出"
        echo
        local default_choice="2"
        if $direct_allowed; then
            if [ "$web_required" = false ] || ! $NEED_WEB_REBUILD; then
                default_choice="1"
            fi
        elif $NEED_WEB_REBUILD; then
            if [ "$web_required" = true ]; then
                default_choice="3"
            fi
        fi
        read -p "请选择 (1-5) [${default_choice}]: " choice
        choice=${choice:-$default_choice}
        echo

        case $choice in
            1)
                if $direct_allowed; then
                    BUILD_STRATEGY="direct"
                    break
                else
                    log_warning "当前没有现成构建产物，无法直接启动，请选择其他选项。"
                fi
                ;;
            2)
                BUILD_STRATEGY="full"
                break
                ;;
            3)
                BUILD_STRATEGY="web-only"
                break
                ;;
            4)
                BUILD_STRATEGY="cpp-only"
                break
                ;;
            5)
                log_info "已退出"
                exit 0
                ;;
            *)
                log_warning "无效选择，请重新输入。"
                ;;
        esac
    done

    log_info "构建策略: $BUILD_STRATEGY"
}

# 执行构建
execute_build() {
    case $BUILD_STRATEGY in
        "direct")
            log_step "1" "跳过构建，直接启动"
            ;;
        "web-only")
            log_step "1" "构建Web前端并重新编译后端(嵌入最新资源)"
            if $WEB_AVAILABLE && [ -f "$PROJECT_ROOT/scripts/build-web.sh" ]; then
                cd "$PROJECT_ROOT"
                ./scripts/build-web.sh --skip-lint
                # 重新编译C++后端以包含最新的嵌入资源
                ./scripts/build.sh build --skip-web
            else
                log_warning "Web构建脚本不存在，跳过Web构建"
                cd "$PROJECT_ROOT"
                ./scripts/build.sh build --skip-web
            fi
            ;;
        "cpp-only")
            log_step "1" "仅构建C++后端"
            cd "$PROJECT_ROOT"
            ./scripts/build.sh build --skip-web
            ;;
        "full")
            log_step "1" "执行完整构建"
            if $WEB_AVAILABLE; then
                log_info "构建包含: C++项目 + Web前端"
                cd "$PROJECT_ROOT"
                ./scripts/build.sh build
            else
                log_info "仅构建C++项目"
                cd "$PROJECT_ROOT"
                ./scripts/build.sh build --skip-web
            fi
            ;;
    esac
}

# 预启动检查
pre_launch_check() {
    log_header "预启动检查"

    # 在启动前再次校验嵌入资源与构建产物的一致性（必要时自动修复）
    ensure_web_embedding_consistent
    
    # 检查可执行文件
    if [ ! -f "$PROJECT_ROOT/build/bin/ems-cpp-v1" ]; then
        log_error "可执行文件不存在: build/bin/ems-cpp-v1"
        log_info "请先运行完整构建"
        exit 1
    fi
    
    # 检查配置文件
    local config_files=("config/system.json" "config/mqtt.conf" "config/devices.json")
    local missing_configs=()
    
    for config in "${config_files[@]}"; do
        if [ -f "$PROJECT_ROOT/$config" ]; then
            log_info "✓ $config"
        else
            missing_configs+=("$config")
        fi
    done
    
    # 生成缺失的配置文件
    if [ ${#missing_configs[@]} -gt 0 ]; then
        log_warning "发现缺失的配置文件，正在生成默认配置..."
        
        if [ -f "$PROJECT_ROOT/scripts/deploy-dev.sh" ]; then
            # 仅运行配置文件生成部分
            cd "$PROJECT_ROOT"
            mkdir -p config
            
            # 生成system.json
            if [ ! -f "config/system.json" ]; then
                cat > "config/system.json" << 'EOF'
{
    "basic": {
        "system_name": "EMS 能源管理系统",
        "device_id": "ems-gateway-001",
        "work_mode": "gateway",
        "listen_port": 9527,
        "api_port": 8081,
        "websocket_port": 8082
    },
    "collection": {
        "interval": 30,
        "timeout": 5000,
        "retry_count": 3,
        "max_concurrent": 10,
        "auto_reconnect": true
    },
    "logging": {
        "level": "info",
        "file_path": "./logs/system.log",
        "console_output": true
    }
}
EOF
                log_info "已生成 config/system.json"
            fi
            
            # 生成mqtt.conf
            if [ ! -f "config/mqtt.conf" ]; then
                if [ -f "config/mqtt.template.conf" ]; then
                    cp "config/mqtt.template.conf" "config/mqtt.conf"
                    log_info "已从模板复制 config/mqtt.conf"
                else
                    cat > "config/mqtt.conf" << 'EOF'
{
  "broker": {
    "host": "127.0.0.1",
    "port": 1883,
    "use_tls": false,
    "ca_file": "",
    "cert_file": "",
    "key_file": ""
  },
  "client": {
    "device_sn": "",
    "device_type": "",
    "username": "",
    "password": "",
    "keep_alive": 60,
    "clean_session": true,
    "qos": 1,
    "retained": false
  },
  "topics": {
    "topic_prefix": "/ext/${deviceSn}/register",
    "data_upload": "up/gateway/report/data",
    "alarm_upload": "up/gateway/report/alarm",
    "alarm_clear": "up/gateway/report/alarm_clear",
    "device_sync": "up/gateway/sync/res",
    "login": "up/gateway/login",
    "command_response": "up/gateway/func/res"
  },
  "security": {
    "sign_method": "hmacsha256",
    "device_type_secret": ""
  }
}
EOF
                    log_info "已生成 config/mqtt.conf"
                fi
            fi
            
            # 生成devices.json
            if [ ! -f "config/devices.json" ]; then
                if [ -f "config/devices.template.json" ]; then
                    cp "config/devices.template.json" "config/devices.json"
                    log_info "已从模板复制 config/devices.json"
                else
                    cat > "config/devices.json" << 'EOF'
{
    "devices": [
        {
            "id": 1,
            "name": "测试设备",
            "protocol": "modbus_tcp",
            "address": "127.0.0.1",
            "port": 502,
            "slave_id": 1,
            "enabled": true,
            "description": "示例Modbus设备"
        }
    ]
}
EOF
                    log_info "已生成 config/devices.json"
                fi
            fi
        fi
    fi
    
    # 创建日志目录
    mkdir -p "$PROJECT_ROOT/logs"
    
    # 检查端口占用
    local ports=(9527 8081 8082)
    for port in "${ports[@]}"; do
        if command -v lsof &> /dev/null; then
            if lsof -ti:$port &> /dev/null; then
                log_warning "端口 $port 已被占用"
            fi
        elif command -v ss &> /dev/null; then
            if ss -tuln | grep -q ":$port "; then
                log_warning "端口 $port 已被占用"
            fi
        fi
    done
    # 确保嵌入资源与构建产物一致（避免前端chunk不匹配导致白屏/404）
    ensure_web_embedding_consistent

    log_success "预启动检查完成"
}

# 启动系统
launch_system() {
    stop_existing_instances
    log_header "启动系统"
    
    # 显示启动信息
    log_info "系统配置:"
    log_info "  Web界面: http://localhost:9527"
    log_info "  API接口: http://localhost:8081"
    log_info "  WebSocket: ws://localhost:8082"
    log_info "  配置目录: $PROJECT_ROOT/config"
    log_info "  日志目录: $PROJECT_ROOT/logs"
    echo
    
    log_success "🚀 启动 $PROJECT_NAME..."
    log_info "使用 Ctrl+C 停止系统"
    echo
    
    # 启动程序（前台守护），保留Shell以便在退出时统一清理Web
    cd "$PROJECT_ROOT"
    ./build/bin/ems-cpp-v1 --config ./config &
    APP_PID=$!
    log_info "主程序已启动，PID=$APP_PID"
    # 等待主程序结束（正常退出或被 Ctrl+C 中断），随后触发 cleanup()
    wait "$APP_PID"
}

stop_existing_instances() {
    if command -v pgrep >/dev/null 2>&1; then
        existing_pids=$(pgrep -f "ems-cpp-v1 --config ./config" || true)
    else
        existing_pids=$(ps aux | grep "ems-cpp-v1 --config ./config" | grep -v grep | awk '{print $2}')
    fi
    if [ -n "$existing_pids" ]; then
        log_warning "检测到已有运行实例: $existing_pids"
        for pid in $existing_pids; do
            log_info "终止历史实例 PID=$pid"
            kill "$pid" 2>/dev/null || true
        done
        sleep 0.5
        if command -v pgrep >/dev/null 2>&1; then
            resid=$(pgrep -f "ems-cpp-v1 --config ./config" || true)
        else
            resid=$(ps aux | grep "ems-cpp-v1 --config ./config" | grep -v grep | awk '{print $2}')
        fi
        if [ -n "$resid" ]; then
            log_warning "部分实例仍在运行，强制终止: $resid"
            for pid in $resid; do
                kill -9 "$pid" 2>/dev/null || true
            done
        fi
    fi
}

# 错误处理
handle_error() {
    log_error "启动过程中发生错误"
    log_info "故障排除建议:"
    echo "  1. 检查系统依赖: ./scripts/deploy-dev.sh --help"
    echo "  2. 重新构建项目: ./scripts/build.sh clean && ./scripts/build.sh build"
    echo "  3. 查看构建日志: cat build/CMakeFiles/CMakeError.log"
    echo "  4. 检查配置文件: ls -la config/"
    echo
    log_info "获取帮助: https://github.com/your-org/ems-cpp-v1/issues"
    exit 1
}

# 信号处理
cleanup() {
    log_warning "正在停止系统..."
    # 优雅终止主程序
    if [ -n "$APP_PID" ] && ps -p "$APP_PID" > /dev/null 2>&1; then
        log_info "尝试终止主程序 (PID=$APP_PID)"
        kill "$APP_PID" 2>/dev/null || true
        sleep 0.5
        if ps -p "$APP_PID" > /dev/null 2>&1; then
            log_warning "主程序仍在运行，执行强制终止 (SIGKILL)"
            kill -9 "$APP_PID" 2>/dev/null || true
        fi
    fi

    # 结束可能残留的 Web/接口/WS 进程（如外部开发服务器）
    # 端口依据项目约定：Web=9527，API=8081，WS=8082
    if command -v lsof >/dev/null 2>&1; then
        for port in 9527 8081 8082; do
            pids=$(lsof -ti:$port 2>/dev/null || true)
            if [ -n "$pids" ]; then
                log_warning "释放端口 $port，终止进程: $pids"
                kill $pids 2>/dev/null || true
                sleep 0.3
                still=$(lsof -ti:$port 2>/dev/null || true)
                if [ -n "$still" ]; then
                    log_warning "进程仍在，占用 $port，强制终止: $still"
                    kill -9 $still 2>/dev/null || true
                fi
            fi
        done
    fi
}

# 显示性能建议
show_performance_tips() {
    if [ "$BUILD_STRATEGY" = "full" ]; then
        echo
        log_header "性能优化建议"
        log_info "💡 为了提高后续启动速度："
        echo "  • 使用 $0 直接启动已构建的项目"
        echo "  • Web文件会嵌入到C++程序中，无需单独部署"
        echo "  • 配置文件修改后无需重新构建"
        echo
    fi
}

# 主函数
main() {
    # 设置错误处理
    trap handle_error ERR
    trap cleanup INT TERM EXIT
    # 解析环境变量 SKIP_WEB（命令行参数在文末 case 处理）
    if [ "${SKIP_WEB}" = "1" ] || [ "${SKIP_WEB}" = "true" ]; then
        FORCE_SKIP_WEB=true
    fi
    
    # 执行启动流程
    show_welcome
    
    log_step "1/7" "系统兼容性检查"
    check_system
    echo

    log_step "2/7" "安装系统依赖"
    install_system_dependencies
    echo

    log_step "3/7" "依赖检查"
    quick_dependency_check
    echo

    log_step "4/7" "项目结构检查"
    check_project_structure
    echo

    log_step "5/7" "构建策略选择"
    choose_build_strategy
    echo

    log_step "6/7" "执行构建"
    execute_build
    echo

    log_step "7/7" "预启动检查"
    pre_launch_check
    echo
    
    # 显示性能建议
    show_performance_tips
    
    # 启动系统
    launch_system
}

# 处理命令行参数
case "${1:-}" in
    "--help"|"-h")
        echo "EMS 能源管理系统一键启动脚本"
        echo
        echo "用法: $0 [选项]"
        echo
        echo "选项:"
        echo "  --help, -h     显示此帮助信息"
        echo "  --version, -v  显示版本信息"
        echo "  --force-build  强制重新构建"
        echo "  --skip-web     跳过Web构建"
        echo
        echo "环境变量:"
        echo "  SKIP_WEB=1|true  跳过Web构建（等效 --skip-web）"
        echo
        echo "功能:"
        echo "  • 自动检查系统环境和依赖"
        echo "  • 智能选择构建策略"
        echo "  • 构建Web前端和C++程序"
        echo "  • 生成默认配置文件"
        echo "  • 启动完整系统"
        echo
        echo "首次运行建议:"
        echo "  ./scripts/deploy-dev.sh  # 完整环境搭建"
        echo "  $0                       # 启动系统"
        echo
        exit 0
        ;;
    "--version"|"-v")
        echo "EMS 能源管理系统 $VERSION"
        echo "构建时间: $(date)"
        echo "支持平台: Linux, macOS"
        exit 0
        ;;
    "--force-build")
        BUILD_STRATEGY="full"
        ;;
    "--skip-web")
        FORCE_SKIP_WEB=true
        ;;
esac

# 执行主函数
main
